﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Threading;
using System;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using WindowsStoreApps.Common.Settings;
using WindowsStoreApps.Model;

namespace WindowsStoreApps.ViewModel
{
    /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class MainViewModel : ViewModelBase, IHandleItemClick
    {
        private IDataService<MainPageDataItem, Exception> _dataService;
        private CancellationTokenSource _tokenSource = null;

        /// <summary>
        /// The <see cref="WelcomeTitle" /> property's name.
        /// </summary>
        public const string WelcomeTitlePropertyName = "WelcomeTitle";

        private string _welcomeTitle = "Welcome to Windows store apps practice";

        /// <summary>
        /// Gets the WelcomeTitle property.
        /// Changes to that property's value raise the PropertyChanged event. 
        /// </summary>
        public string WelcomeTitle
        {
            get
            {
                return _welcomeTitle;
            }

            private set { this.Set("WelcomeTitle", ref _welcomeTitle, value); }
        }

        private ObservableCollection<MainPageDataItem> _items = new ObservableCollection<MainPageDataItem>();
        public ObservableCollection<MainPageDataItem> Items
        {
            get { return _items; }
            private set { this.Set("Items", ref _items, value); }
        }

        private bool _loading = false;
        public bool Loading
        {
            get { return _loading; }
            private set { this.Set("Loading", ref _loading, value); }
        }

        private RelayCommand _settingCommand;
        public RelayCommand SettingCommand
        {
            get { return _settingCommand; }
            set { this.Set("SettingCommand", ref _settingCommand, value); }
        }

        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel(IDataService<MainPageDataItem, Exception> dataService)
        {
            _dataService = dataService;

            if (ViewModelBase.IsInDesignModeStatic)
            {
                _dataService = dataService;
                _dataService.GetData(
                    (item, error) =>
                    {
                        if (error == null)
                        {
                            this.Items.Add(item);
                        }
                    });
            }
            else
            {
                initDataAsync(dataService);
            }

            SettingCommand = new RelayCommand(() => GlobalAppSettingAgent.Default.TriggerSettingPanel());
        }

        private Task initDataAsync(IDataService<MainPageDataItem, Exception> dataService)
        {
            DispatcherHelper.Initialize();
            Loading = true;
            _tokenSource = null;
            _tokenSource = new CancellationTokenSource();

            _dataService = dataService;
            return _dataService.GetDataAsync(_tokenSource.Token,
                (result) => // Result call back action
                {
                    if (result.Exp != null)
                    {
                        var errorAction = DispatcherHelper.RunAsync(
                            () =>
                            {
                                MainPageDataItem expItem = new MainPageDataItem(result.Exp.GetType().ToString(),
                                    result.Exp.ToString(), string.Empty);
                                this.Items.Add(expItem);
                            });
                        return;
                    }

                    var resultAction = DispatcherHelper.RunAsync(
                        () =>
                        {
                            this.Items.Add(result.Item);
                        });
                },
                () => // Completed action
                {
                    var completedAction = DispatcherHelper.UIDispatcher.RunIdleAsync(
                        (p) =>
                        {
                            Loading = false;
                        });
                });
        }

        ////public override void Cleanup()
        ////{
        ////    // Clean up if needed

        ////    base.Cleanup();
        ////}

        public void HandleItemClicked(object sender, Windows.UI.Xaml.Controls.ItemClickEventArgs e)
        {
            if (e.ClickedItem is MainPageDataItem)
            {
                DataActionHandler.Default.HandleAction(e.ClickedItem as MainPageDataItem);
            }
        }

        ~MainViewModel()
        { }
    }
}